<template>
  <div class="permission-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="handleAdd">新增权限</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="菜单权限" value="menu" />
            <el-option label="按钮权限" value="button" />
            <el-option label="数据权限" value="data" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源标识">
          <el-input v-model="searchForm.resource" placeholder="请输入资源标识" clearable />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.action" placeholder="请选择操作类型" clearable>
            <el-option label="查看" value="view" />
            <el-option label="新增" value="create" />
            <el-option label="编辑" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="导出" value="export" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item label="所属菜单">
          <el-select v-model="searchForm.menu_id" placeholder="请选择菜单" clearable>
            <el-option
              v-for="menu in menuOptions"
              :key="menu.id"
              :label="menu.title"
              :value="menu.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="权限名称" />
        <el-table-column prop="type_name" label="权限类型" width="100" />
        <el-table-column prop="resource" label="资源标识" width="120" />
        <el-table-column prop="action_name" label="操作类型" width="100" />
        <el-table-column prop="code" label="权限编码" />
        <el-table-column prop="menu.title" label="所属菜单" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current_page"
          v-model:page-size="pagination.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择权限类型" style="width: 100%" @change="handleTypeChange">
            <el-option label="菜单权限" value="menu" />
            <el-option label="按钮权限" value="button" />
            <el-option label="数据权限" value="data" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源标识" prop="resource" v-if="form.type !== 'menu'">
          <el-input v-model="form.resource" placeholder="例如：users, roles" />
        </el-form-item>
        <el-form-item label="操作类型" prop="action" v-if="form.type !== 'menu'">
          <el-select v-model="form.action" placeholder="请选择操作类型" style="width: 100%">
            <el-option label="查看" value="view" />
            <el-option label="新增" value="create" />
            <el-option label="编辑" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="导出" value="export" />
            <el-option label="导入" value="import" />
            <el-option label="审核" value="audit" />
            <el-option label="分配" value="assign" />
            <el-option label="重置" value="reset" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="form.code" placeholder="自动生成或手动输入" />
        </el-form-item>
        <el-form-item label="所属菜单" prop="menu_id">
          <el-select v-model="form.menu_id" placeholder="请选择菜单" clearable style="width: 100%">
            <el-option
              v-for="menu in menuOptions"
              :key="menu.id"
              :label="menu.title"
              :value="menu.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/date'

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增权限')
const formRef = ref(null)
const menuOptions = ref([])

const searchForm = reactive({
  name: '',
  type: '',
  resource: '',
  action: '',
  code: '',
  menu_id: '',
})

const form = reactive({
  id: null,
  name: '',
  code: '',
  type: 'button',
  resource: '',
  action: '',
  menu_id: '',
  remark: '',
})

const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' },
  ],
  resource: [
    { required: true, message: '请输入资源标识', trigger: 'blur', validator: (rule, value, callback) => {
      if (form.type !== 'menu' && !value) {
        callback(new Error('请输入资源标识'))
      } else {
        callback()
      }
    }},
  ],
  action: [
    { required: true, message: '请选择操作类型', trigger: 'change', validator: (rule, value, callback) => {
      if (form.type !== 'menu' && !value) {
        callback(new Error('请选择操作类型'))
      } else {
        callback()
      }
    }},
  ],
}

const tableData = ref([])
const pagination = reactive({
  current_page: 1,
  page_size: 15,
  total: 0,
})

// 加载菜单选项
const loadMenuOptions = async () => {
  try {
    const res = await request.get('/menus?tree=1')
    if (res.code === 200) {
      menuOptions.value = flattenMenus(res.data)
    }
  } catch (error) {
    console.error('加载菜单失败:', error)
  }
}

// 扁平化菜单树
const flattenMenus = (menus) => {
  const result = []
  const flatten = (items, level = 0) => {
    items.forEach(item => {
      result.push({
        id: item.id,
        title: '  '.repeat(level) + item.title,
        ...item,
      })
      if (item.children && item.children.length > 0) {
        flatten(item.children, level + 1)
      }
    })
  }
  flatten(menus)
  return result
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current_page,
      page_size: pagination.page_size,
      ...searchForm,
    }
    const res = await request.get('/permissions', { params })
    if (res.code === 200) {
      tableData.value = res.data.data
      pagination.total = res.data.total
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current_page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    resource: '',
    action: '',
    code: '',
    menu_id: '',
  })
  handleSearch()
}

// 类型变化
const handleTypeChange = () => {
  // 根据类型自动生成编码
  if (form.type !== 'menu' && form.resource && form.action) {
    form.code = `${form.resource}.${form.action}`
  }
  // 清空资源标识和操作类型
  if (form.type === 'menu') {
    form.resource = ''
    form.action = ''
    form.code = ''
  }
}

// 监听资源标识和操作类型变化，自动生成编码
watch([() => form.resource, () => form.action], () => {
  if (form.type !== 'menu' && form.resource && form.action) {
    form.code = `${form.resource}.${form.action}`
  }
})

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增权限'
  Object.assign(form, {
    id: null,
    name: '',
    code: '',
    type: 'button',
    resource: '',
    action: '',
    menu_id: '',
    remark: '',
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑权限'
  Object.assign(form, {
    id: row.id,
    name: row.name,
    code: row.code,
    type: row.type || 'button',
    resource: row.resource || '',
    action: row.action || '',
    menu_id: row.menu_id,
    remark: row.remark,
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该权限吗？', '提示', {
      type: 'warning',
    })
    const res = await request.delete(`/permissions/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    if (form.id) {
      const res = await request.put(`/permissions/${form.id}`, form)
      if (res.code === 200) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        loadData()
      }
    } else {
      const res = await request.post('/permissions', form)
      if (res.code === 200) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        loadData()
      }
    }
  } catch (error) {
    if (error.errors) {
      ElMessage.error('验证失败，请检查输入')
    } else {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.clearValidate()
}

// 分页
const handleSizeChange = (size) => {
  pagination.page_size = size
  loadData()
}

const handlePageChange = (page) => {
  pagination.current_page = page
  loadData()
}

onMounted(() => {
  loadMenuOptions()
  loadData()
})
</script>

<style scoped lang="scss">
.permission-container {
  // padding 由 app-container 统一管理，这里不需要额外的 padding
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

